package com.xnx3.j2ee.util;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import com.xnx3.FileUtil;
import com.xnx3.StringUtil;
import java.io.File;
import java.security.Key;
import java.security.SecureRandom;
import sun.misc.BASE64Encoder;
import sun.misc.BASE64Decoder;

/**
 * DSA加密解密
 * 会在jre根目录下自动建立dsaKey.txt的混淆字符串
 * 后面xnx3-util版本升到中央仓库后将继承 com.xnx3.DSAUtil
 * @author 管雷鸣
 *
 */
public class DSAUtil {
	/*指定加密/解密使用的密匙*/
    private static Key key;
    public static DSAUtil dsa;	//初始化后静态的，可供直接用的
    
    static {
    	String key = "wm is very good , good !";
		try {
//			System.out.println(new VersionUtil().getClass());
			String path = System.getProperty("java.home");
//			path = path.replace("WEB-INF/classes/", "");
//			System.out.println(path);
			
			File file = new File(path);
//			String parentPath = file.getParentFile().getParentFile().getPath();
			String dasKeyPath = file.getPath()+File.separatorChar+"desKey.txt";
			//ConsoleUtil.info("dasKeyPath:"+dasKeyPath);
			if(!FileUtil.exists(dasKeyPath)) {
				//创建
				if(!FileUtil.write(dasKeyPath, StringUtil.getRandom09AZ(16))) {
					//创建失败没有写出成功
					ConsoleUtil.error("写出文件 "+dasKeyPath +" 失败！可能没有写出权限导致。如果后面有使用DAS加密解密相关出现异常，那可能就是这里的事");
				}
			}
			key = FileUtil.read(dasKeyPath);
		} catch (Exception e) {
			e.printStackTrace();
		}
		key = key.trim();
//		ConsoleUtil.info("key:"+key);
		dsa = new DSAUtil(key);
    }
    
    /**
     * @deprecated
     */
    public DSAUtil() {
    	//System.out.println("please use DSAUtil(str)");
    }
    
    /**
     * DSA加密解密
     * @param confuseKey 用于加密混淆的密匙,传入的字符串长度必须是8的倍数
     */
    public DSAUtil(String confuseKey) {
    	try {
            /*防止Linux下随机生成key*/
            SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
            secureRandom.setSeed(confuseKey.getBytes());

            KeyGenerator keyGenerator = KeyGenerator.getInstance("DES");
            //keyGenerator.init(new SecureRandom(KEY_STR.getBytes()));
            keyGenerator.init(secureRandom);
            key = keyGenerator.generateKey();
            keyGenerator = null;
        }catch (Exception e){
            throw new RuntimeException(e);
        }
	}
    
    /**
     * 对字符串进行DES加密，返回BASE64编码的加密字符串
     * @param string
     * @return
     */
    public String encrypt(String string){
        BASE64Encoder base64Encoder = new BASE64Encoder();
        try {
            byte[] strBytes = string.getBytes("UTF-8");
            Cipher cipher = Cipher.getInstance("DES");
            cipher.init(Cipher.ENCRYPT_MODE,key);
            byte[] encryptStrBytes = cipher.doFinal(strBytes);
            return base64Encoder.encode(encryptStrBytes);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 对BASE64编码的加密字符串进行解密，返回解密后的字符串
     * @param str
     * @return
     */
    public String decrypt(String str){
        BASE64Decoder base64Decoder = new BASE64Decoder();
        try {
            byte[] strBytes = base64Decoder.decodeBuffer(str);
            Cipher cipher = Cipher.getInstance("DES");
            cipher.init(Cipher.DECRYPT_MODE,key);
            byte[] decryptStrBytes = cipher.doFinal(strBytes);
            return new String(decryptStrBytes,"UTF-8");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 给shell执行用的。
     * 
     * cd ~
     * wget http://down.zvo.cn/wm/version/wm-2.20.jar -O wm.jar
     * wget http://down.zvo.cn/jar/xnx3-util-1.9.jar -O xnx3-util.jar
     * dsa_str=`java -cp ./wm.jar:./xnx3-util.jar  com.xnx3.j2ee.util.DSAUtil 这里是跟上要加密的字符串`
     * echo $dsa_str;
     * @param args
     */
    public static void main(String[] args) {
    	if(args.length == 0) {
			System.out.println("please input string");
			return;
		}
		String str = args[0];	//输入，传入的
		
		System.out.println(dsa.encrypt(str));
    }
}
